package com.vito.act.tool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;

import com.vito.act.dao.ActExTableColsMapper;
import com.vito.act.dao.ActExTableMapper;
import com.vito.act.model.ActExSaveModel;
import com.vito.act.model.ActExTableColsModel;
import com.vito.act.model.ActExTableModel;
import com.vito.act.tool.ActivitiTool;
import com.vito.base.authoriza.dao.SQLAdapterMapper;
import com.vito.base.util.Contants;
import com.vito.base.util.Pty;
import com.vito.base.util.SpringApplicationContext;
import com.vito.base.util.Validata;
import com.vito.oa.act.dao.OaActExMapper;

public class CreateCodeServerTask implements JavaDelegate {
	private static String dialect="oracle";
	static{
		Pty pty  = null;
		try {
			pty = Pty.get("conf/jdbc");
		} catch (Exception e) {
		}
		if(pty!=null){
			dialect = pty.getProp("sql.dialect");
		}
	}
	private Expression type; //编号类型
	private Expression format;//日期格式
	private Expression prefix;//前缀
	private Expression suffix;//后缀
	private Expression formId;//表单
	private Expression formNodeId;//表单所属节点
	
	private OaActExMapper codeMapper =SpringApplicationContext.getApplicationContext().getBean(OaActExMapper.class);
	private ActExTableMapper tableMapper =SpringApplicationContext.getApplicationContext().getBean(ActExTableMapper.class);
	private SQLAdapterMapper sqlMapper =SpringApplicationContext.getApplicationContext().getBean(SQLAdapterMapper.class);
	private ActExTableColsMapper colMapper =SpringApplicationContext.getApplicationContext().getBean(ActExTableColsMapper.class);
	@Override
	public void execute(DelegateExecution execution) throws Exception {
		String typeVal = (String)type.getValue(execution);
		String formatVal = (String)format.getValue(execution);
		String prefixVal = (String)prefix.getValue(execution);
		String suffixValue = (String)suffix.getValue(execution);
		String formIdValue = (String)formId.getValue(execution);
		String formNodeValue = (String)formNodeId.getValue(execution);
		
		ExecutionEntity entity = (ExecutionEntity) execution;
		String businessId = execution.getProcessBusinessKey();
		String processKey = entity.getProcessDefinition().getKey();
		
		//通过nodeId获取taskId（若存在相同node取最后一个）
		List<HistoricTaskInstance>  taskList =  ActivitiTool.getHistoryService().createHistoricTaskInstanceQuery()
				.taskDefinitionKey(formNodeValue)
				.processInstanceId(entity.getProcessInstanceId())
//				.orderByTaskCreateTime()
				.list();
		
		String taskId = null;
		if(taskList != null && !taskList.isEmpty()){
			taskId = taskList.get(taskList.size()-1).getId();
		}
		//生成code
		String code = codeMapper.queryCodeSeq(typeVal, formatVal, prefixVal, suffixValue);

		//获取执行sql
		Map<String,Object> data = new HashMap<String,Object>();
		data.put(formIdValue, code);
		ActExSaveModel model = new ActExSaveModel();
		initUpdateSql(businessId,processKey,taskId,formNodeValue,data,model);
		
		//编号插入表单
		if(model.getSql()!=null&&model.getSql().length()>0){
			model.getParam_map().put("sql", model.getSql().toString());
			model.getParam_map().put("databaseId", dialect);
			sqlMapper.updateDataBysql(model.getParam_map());
		}
	}
	
	private void initUpdateSql(String businessId,String processKey,String taskId,String nodeId,Map<String,Object> data,ActExSaveModel sqlModel){
		Map<String,Object> map1 = new HashMap<String,Object>();
		map1.put("key", processKey);
		map1.put("processNodeId", nodeId);
		
		List<ActExTableModel> tables = tableMapper.queryActExTableByKeyAndNode(map1);
		if(tables != null && !tables.isEmpty()){
			ActExTableModel tab = tables.get(0);
			String tableKey = tab.getTableKey();
			String tableName = Contants.TABLE_FIRST_NAME+tableKey;

			String pkName = "";
			ActExTableColsModel actExTableColsModel = new ActExTableColsModel();
			actExTableColsModel.setCheckeds(new String[]{tableKey});
			List<ActExTableColsModel> pkCol = colMapper.queryTablePKAndFk(actExTableColsModel);
			
			for(ActExTableColsModel colModel:pkCol){
				pkName = colModel.getColName();
			}
			boolean isMain = Validata.isNullOrEmpty(taskId)?true:false;
			data.put(pkName, businessId);
			
			ActivitiFormDataTool.getInsOrUpdSql(Contants.FORM_OPER_UPD, tableName, data, pkName, taskId, isMain, sqlModel);
		}
	}

}
